package com.imagecollector.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.imagecollector.common.constant.TaskConstant;
import com.imagecollector.common.exception.DataConflictException;
import com.imagecollector.controller.common.PictureDTOAndPicture;
import com.imagecollector.domain.dto.TaskAbandonRecordDTO;
import com.imagecollector.domain.dto.TaskReceiverRecordDTO;
import com.imagecollector.domain.entity.*;
import com.imagecollector.domain.dto.PictureDTO;
import com.imagecollector.domain.vo.ScenicAndExibitorNames;
import com.imagecollector.domain.vo.TaskVo;
import com.imagecollector.mapper.AppletTaskMapper;
import com.imagecollector.mapper.PictureMapper;
import com.imagecollector.mapper.TaskReceiverRecordMapper;
import com.imagecollector.mapper.TaskSubmitRecordMapper;
import com.imagecollector.service.IDistrictService;
import com.imagecollector.service.IAppletTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imagecollector.service.ITaskSubmitRecordService;
import lombok.extern.slf4j.Slf4j;

import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


/**
 * <p>
 * 任务表 服务实现类
 * </p>
 *
 * @author wrf
 * @since 2024-07-31
 */
@Service
@Slf4j
public class AppletTaskServiceImpl extends ServiceImpl<AppletTaskMapper, Task> implements IAppletTaskService {

    @Autowired
    private AppletTaskMapper appletTaskMapper;
    @Autowired
    private TaskReceiverRecordServiceImpl taskReceiverRecordService;
    @Autowired
    private ITaskSubmitRecordService taskSubmitRecordService;
    @Autowired
    private PictureServiceImpl pictureService;
    @Autowired
    private TaskAbandonRecordServiceImpl taskAbandonRecordService;
    @Autowired
    private IDistrictService districtService;
    @Autowired
    private PictureMapper pictureMapper;
    @Autowired
    private TaskSubmitRecordMapper taskSubmitRecordMapper;
    @Autowired
    private TaskReceiverRecordMapper taskReceiverRecordMapper;



    public Integer getIsRepeatedlyReceive(Integer taskId){
        log.info(appletTaskMapper.selectById(taskId).getIsRepeatedlyReceive()+"");
        Integer isRepeatedlyReceive = appletTaskMapper.selectById(taskId).getIsRepeatedlyReceive();
        return isRepeatedlyReceive;
    }


    @Override
    public IPage<TaskVo> selectPage(Integer pageNum, Integer pageSize, Integer districtId) {
        IPage<TaskVo> taskVoPage = new Page<>(pageNum, pageSize);
        IPage<TaskVo> taskVoIPage = appletTaskMapper.selectByPage(taskVoPage, districtId);
        taskVoIPage.getRecords().forEach(taskVo -> {
            taskVo.setDistrictName(districtService.getDistrictFullName(taskVo.getDistrictId()));
        });
        return taskVoIPage;
    }

    @Override
    public IPage<TaskVo> selectMyTaskPage(Integer pageNum, Integer pageSize, Integer districtId, Integer userId, Integer status) {
        // 先查询是否有过期未提交的任务
        if (!taskReceiverRecordMapper.expirList(userId,TaskConstant.TASK_STATUS_RECEIVED).isEmpty()){
            taskReceiverRecordMapper.expirList(userId,TaskConstant.TASK_STATUS_RECEIVED).forEach(taskReceiverRecord -> {
                // 先将接受表更新状态为-3
                taskReceiverRecord.setStatus(TaskConstant.TASK_STATUS_EXPIRED);
                taskReceiverRecordMapper.updateById(taskReceiverRecord);
                // 往放弃表添加数据
                TaskAbandonRecord taskAbandonRecord = new TaskAbandonRecord();
                taskAbandonRecord.setTaskId(taskReceiverRecord.getTaskId());
                taskAbandonRecord.setUserId(taskReceiverRecord.getUserId());
                taskAbandonRecord.setReceiverRecordId(taskReceiverRecord.getId());
                taskAbandonRecordService.save(taskAbandonRecord);
            });
        }

        IPage<TaskVo> taskVoPage = new Page<>(pageNum, pageSize);
        IPage<TaskVo> taskVoIPage = appletTaskMapper.selectMyTaskPage(taskVoPage, districtId, userId, status);
        taskVoIPage.getRecords().forEach(taskVo -> {
            taskVo.setDistrictName(districtService.getDistrictFullName(taskVo.getDistrictId()));
        });

        return taskVoIPage;
    }

    @Override
    public TaskVo selectDetail(Integer taskId) {
        Task task = appletTaskMapper.selectById(taskId);
        TaskVo taskVo = new TaskVo();
        BeanUtils.copyProperties(task,taskVo);
        taskVo.setDistrictName(districtService.getDistrictFullName(task.getDistrictId()));
        return taskVo;
    }

    @Override
    @Transactional
    public List<ScenicAndExibitorNames> selectExhibitorNames(String customerServiceRemarkScenic, String customerServiceRemarkExhibits) {

        List<ScenicAndExibitorNames> exhibitorNames = pictureMapper.selectExhibitorNames(customerServiceRemarkScenic,customerServiceRemarkExhibits);
        return exhibitorNames;
    }


    @Override
    @Transactional
    public void receive(TaskReceiverRecordDTO taskReceiverRecordDTO) {
        // 更新任务表状态
        if (getIsRepeatedlyReceive(taskReceiverRecordDTO.getTaskId()) == 0){
            Task task = new Task();
            task.setId(taskReceiverRecordDTO.getTaskId());
            task.setStatus(TaskConstant.TASK_STATUS_RECEIVED);
            appletTaskMapper.updateById(task);
        }
        // 往任务接收表插入数据
        TaskReceiverRecord taskReceiverRecord = new TaskReceiverRecord();
        BeanUtils.copyProperties(taskReceiverRecordDTO,taskReceiverRecord);
        taskReceiverRecord.setStatus(TaskConstant.TASK_STATUS_RECEIVED);
        taskReceiverRecordService.save(taskReceiverRecord);

    }

    @Override
    @Transactional
    public void submit(PictureDTO pictureDTO,Integer receiverRecordId) throws JsonProcessingException {

        TaskSubmitRecord taskSubmitRecord1 = taskSubmitRecordService.getSubmitRecord(pictureDTO.getTaskId(), pictureDTO.getUserId(), receiverRecordId);
        if (Objects.isNull(taskSubmitRecord1)){
            // 用户首次提交
            Picture picture = PictureDTOAndPicture.PictureVoToPicture(pictureDTO);
            Integer isRepeatedlyReceive = appletTaskMapper.selectById(picture.getTaskId()).getIsRepeatedlyReceive();
            if (isRepeatedlyReceive == 0){  // 如果非群发任务
                // 更新任务表状态
                Task task = new Task();
                task.setId(picture.getTaskId());
                task.setStatus(TaskConstant.TASK_STATUS_FINISHED);
                appletTaskMapper.updateById(task);
            }

            // 向任务提交表插入数据
            TaskSubmitRecord taskSubmitRecord = new TaskSubmitRecord();
            taskSubmitRecord.setStatus(TaskConstant.TASK_STATUS_FINISHED);
            taskSubmitRecord.setUserId(picture.getUserId());
            taskSubmitRecord.setRemark(pictureDTO.getRemark());
            taskSubmitRecord.setReceiverRecordId(receiverRecordId);
            taskSubmitRecord.setTaskId(picture.getTaskId());

            taskSubmitRecordMapper.insert(taskSubmitRecord);

            // 更新任务接受表状态
            QueryWrapper<TaskReceiverRecord> queryWrapper = new QueryWrapper<>();
            TaskReceiverRecord taskReceiverRecord = new TaskReceiverRecord();
            taskReceiverRecord.setUserId(picture.getUserId());
            taskReceiverRecord.setTaskId(picture.getTaskId());
            taskReceiverRecord.setId(receiverRecordId);
            taskReceiverRecord.setStatus(TaskConstant.TASK_STATUS_FINISHED);

            queryWrapper.eq("user_id", taskReceiverRecord.getUserId());
            queryWrapper.eq("task_id", taskReceiverRecord.getTaskId());
            queryWrapper.eq("id", taskReceiverRecord.getId());

            taskReceiverRecordService.update(taskReceiverRecord,queryWrapper);

            // 往图片表插入数据
//        QueryWrapper<Picture> queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("task_id", picture.getTaskId());
//        queryWrapper1.eq("user_id", picture.getUserId());
//        pictureService.saveOrUpdate(picture,queryWrapper1);
            log.info("submitRecordId: "+taskSubmitRecord.getId());
            picture.setSubmitRecordId(taskSubmitRecord.getId());
            pictureService.save(picture);
        }else if (Objects.equals(taskSubmitRecord1.getStatus(), TaskConstant.TASK_STATUS_REJECTED)){
            // 用户审核失败再次提交
            Picture picture = pictureService.getPicture(pictureDTO.getTaskId(), pictureDTO.getUserId(), taskSubmitRecord1.getId());
            String picUrl = PictureDTOAndPicture.urlToString(pictureDTO.getUrl());
            picture.setUrl(picUrl);
            pictureService.updateById(picture);
            taskSubmitRecord1.setStatus(TaskConstant.TASK_STATUS_FINISHED);
            taskSubmitRecordMapper.updateById(taskSubmitRecord1);
            TaskReceiverRecord recordServiceById = taskReceiverRecordService.getById(taskSubmitRecord1.getReceiverRecordId());
            recordServiceById.setStatus(TaskConstant.TASK_STATUS_FINISHED);
            taskReceiverRecordService.updateById(recordServiceById);
            Task task = appletTaskMapper.selectById(picture.getTaskId());
            if (task.getIsRepeatedlyReceive() == 0){
                task.setStatus(TaskConstant.TASK_STATUS_FINISHED);
                appletTaskMapper.updateById(task);
            }
        }else {
            throw new DataConflictException("该任务已提交过");
        }



    }

    @Override
    @Transactional
    public void giveup(TaskAbandonRecordDTO taskAbandonRecordDTO) {
        // 更新任务列表状态
        if (getIsRepeatedlyReceive(taskAbandonRecordDTO.getTaskId()) == 0){
            Task task = new Task();
            task.setId(taskAbandonRecordDTO.getTaskId());
            task.setStatus(TaskConstant.TASK_STATUS_PUBLISHED);
            appletTaskMapper.updateById(task);
        }

        // 更新任务接取表中的状态
        QueryWrapper<TaskReceiverRecord> queryWrapper = new QueryWrapper<>();
        TaskReceiverRecord taskReceiverRecord = new TaskReceiverRecord();
        taskReceiverRecord.setTaskId(taskAbandonRecordDTO.getTaskId());
        taskReceiverRecord.setUserId(taskAbandonRecordDTO.getUserId());
        taskReceiverRecord.setStatus(TaskConstant.TASK_STATUS_USER_ABANDONS);
        queryWrapper.eq("task_id", taskReceiverRecord.getTaskId());
        queryWrapper.eq("user_id", taskReceiverRecord.getUserId());
        queryWrapper.eq("id", taskAbandonRecordDTO.getReceiverRecordId());
        taskReceiverRecordService.update(taskReceiverRecord, queryWrapper);

        // 向任务放弃表插入数据
        TaskAbandonRecord taskAbandonRecord = new TaskAbandonRecord();
        BeanUtils.copyProperties(taskAbandonRecordDTO,taskAbandonRecord);
        taskAbandonRecordService.save(taskAbandonRecord);


    }




}
